package net.xfok.xdict;

import java.io.File;
import java.util.Iterator;
import java.util.Map;

import net.xfok.dict.DictEngine;
import net.xfok.dict.Location;
import net.xfok.file.FileUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;



/**
 * @author YangHua
 *
 */
public class Dictionary extends Activity implements OnClickListener,OnItemClickListener {
    /** Called when the activity is first created. */
	private static final String TAG="Dictionary";
	private ProgressDialog progress = null;
	private DictEngine engine;
	private EditText inputKey;
	private Button btSearch;
	private ListView indexList;
	private TextView wordText;
	private TextView resultText;
	private TextView resultFound;
	private IndexAdapter indexAdapter;
	Map<String, Location> result;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
        inputKey=(EditText)findViewById(R.id.key);
        btSearch=(Button)findViewById(R.id.button_search);
        indexList=(ListView)findViewById(R.id.index_list);
        wordText=(TextView)findViewById(R.id.word_text);
        resultText=(TextView)findViewById(R.id.result_text);
        resultFound=(TextView)findViewById(R.id.result_found);
        setViews();  
        loadDict();
    }
    
    private void setViews(){	
    	btSearch.setOnClickListener(this);
    	wordText.setOnClickListener(this);
    	indexList.setOnItemClickListener(this);
    	inputKey.setOnEditorActionListener(onEditorActionListener);	
    	inputKey.setCursorVisible(false);
    	inputKey.setImeActionLabel(getResources().getText(R.string.btn_search), MotionEvent.ACTION_DOWN);
    }
      
    private OnEditorActionListener onEditorActionListener=new OnEditorActionListener(){
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			// TODO Auto-generated method stub
			Log.i(TAG, "action="+actionId);
			String key=inputKey.getText().toString().trim();
			if(!key.equals("")){
				setResult(key);
			}
			return false;
		}
    };   
	
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.button_search:
				String key=inputKey.getText().toString();  	
		    	setResult(key);
		    	break;
			case R.id.word_text:
				Log.i(TAG, "Speak");
//				speak(wordText.getText().toString());
				break;
		}  	
    }
	
	public void onItemClick(AdapterView<?> lv, View v, int position, long id) {
		String index=(String)lv.getAdapter().getItem(position);
		if(index!=null&&!index.equals("")){
			setText(index);
		}
	}
	private void loadDict(){
		if (!DictEngine.isValidDictionary(DictConstant.DICT_PATH,
				DictConstant.DICT_NAME)) {
			this.progress = ProgressDialog.show(this,
					getResources().getText(R.string.dialog_title_loading),
					getResources().getText(R.string.dialog_message_loading),
					true);
			AsyncTask<String, ProgressDialog, String[]> asyncTask = new AsyncTask<String, ProgressDialog, String[]>() {
				protected String[] doInBackground(String... params) {
					try {
						if (!new File(DictConstant.DICT_PATH).exists()) {
							if(new File(DictConstant.DICT_PATH).mkdirs()){
								Log.i(TAG, "=======>mkdir"+DictConstant.DICT_PATH);
							}	
						}
						if (!new File(DictConstant.DICT_PATH + DictConstant.DICT_NAME + DictEngine.DICT_IFO_EXT).exists()) {
							FileUtil.copy(Dictionary.this,DictConstant.DICT_NAME + DictEngine.DICT_IFO_EXT,
									DictConstant.DICT_PATH + DictConstant.DICT_NAME + DictEngine.DICT_IFO_EXT, 0);
							Log.i(TAG, "=======>copy file : "+DictConstant.DICT_NAME + DictEngine.DICT_IFO_EXT);
						}
						if (!new File(DictConstant.DICT_PATH + DictConstant.DICT_NAME + DictEngine.DICT_YAIDX_EXT).exists()) {
							FileUtil.copy(Dictionary.this,DictConstant.DICT_NAME + DictEngine.DICT_YAIDX_EXT,
									DictConstant.DICT_PATH + DictConstant.DICT_NAME + DictEngine.DICT_YAIDX_EXT, 0);
							Log.i(TAG, "=======>copy file : "+DictConstant.DICT_NAME + DictEngine.DICT_YAIDX_EXT);
						}										
						if (!new File(DictConstant.DICT_PATH + DictConstant.DICT_NAME
								+ DictEngine.DICT_DZ_EXT).exists()) {
							FileUtil.copy(Dictionary.this,DictConstant.DICT_NAME + DictEngine.DICT_DZ_EXT,
									DictConstant.DICT_PATH + DictConstant.DICT_NAME + DictEngine.DICT_DZ_EXT, 3);
							Log.i(TAG, "=======>copy file : "+DictConstant.DICT_NAME + DictEngine.DICT_DZ_EXT);
						}
						if (!new File(DictConstant.DICT_PATH + DictConstant.DICT_NAME + DictEngine.DICT_IDX_EXT).exists()) {
							FileUtil.copy(Dictionary.this,DictConstant.DICT_NAME + DictEngine.DICT_IDX_EXT,
									DictConstant.DICT_PATH + DictConstant.DICT_NAME + DictEngine.DICT_IDX_EXT, 4);
							Log.i(TAG, "=======>copy file : "+DictConstant.DICT_NAME + DictEngine.DICT_IDX_EXT);
						}	
						if (DictEngine.isValidDictionary(
								DictConstant.DICT_PATH, DictConstant.DICT_NAME)) {
							engine = new DictEngine(DictConstant.DICT_PATH,
									DictConstant.DICT_NAME);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String[] result) {
					if (Dictionary.this.progress != null && engine != null) {
						Dictionary.this.progress.dismiss();
						Dictionary.this.progress = null;
						setResult(DictConstant.DEFAULT_KEY);
					}
				}
			};
			asyncTask.execute(null);
		} else {
			engine = new DictEngine(DictConstant.DICT_PATH,
					DictConstant.DICT_NAME);
			if (engine != null) {
				setResult(DictConstant.DEFAULT_KEY);
			}
		}	
    }
	
    private void setResult(String key){
    	if(key==null||key.equals("")){
    		key=DictConstant.DEFAULT_KEY;
    	}
    	if(engine!=null){
    		result=engine.getSearchMatchList(key);
    	}
    	setIndex(key.trim());
    	setText(key.trim());   	
    }
    
    private void setText(String key){    	
    	String mean=getResources().getText(R.string.not_found).toString();
    	String wKey=key;
    	String wMean=lookup(key);
    	if(wMean!=null){
    		mean=wMean;
    		wKey=key;
    	}else{	
    		if(indexList.getAdapter().getCount()>0){
    			String index=(String)indexList.getAdapter().getItem(0);
    			if(index!=null&&!index.equals("")){
    				mean=lookup(index);
    				wKey=index;
    			}
    		}
    	}
    	wordText.setText(wKey+" ");
    	resultText.setText(mean);
    	inputKey.setText(key);
    }
    
    private void setIndex(String key){ 
    	indexAdapter=new IndexAdapter(this);  
    	long start = System.currentTimeMillis();
    	if(result!=null&&result.size()>0){
    		Iterator it=result.entrySet().iterator();
    		while(it.hasNext()){
    			Map.Entry entry = (Map.Entry) it.next();
    			indexAdapter.add(entry.getKey().toString());
    		}
    	}
    	setFound(indexAdapter.getCount());
    	if(indexAdapter.getCount()<DictConstant.DEFAULT_COUNT){
    		for(int i=indexAdapter.getCount();i<DictConstant.DEFAULT_COUNT;i++){
    			indexAdapter.add(new String());
    		}
    	}
    	long end = System.currentTimeMillis();
        Log.i(TAG, "set index time:"+(end-start));
    	indexList.setAdapter(indexAdapter);
    }
    
    private void setFound(int count){
    	String text=String.format(getResources().getText(R.string.found_result).toString(), count);
    	resultFound.setText(text);
    }
    
    public String lookup(String key){   	
    	String mean=null;
        try {
        	long start = System.currentTimeMillis(); 
        	if(engine!=null){
        		mean=engine.getExplanation(result.get(key));
        	}
            long end = System.currentTimeMillis();
            Log.i(TAG, "look up time:"+(end-start));
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return mean;
    }
}